package com.jmlambert.droidmc;

import android.content.SharedPreferences; 

import java.io.BufferedReader; 
import java.io.BufferedWriter; 
import java.io.OutputStreamWriter; 
import java.io.InputStreamReader; 
import java.io.PrintWriter; 
import java.net.InetAddress; 
import java.net.Socket; 

import com.jmlambert.droidmc.R;

import android.preference.PreferenceManager; 

import android.util.Log; 

public class TCPClient implements Runnable { 

	public static final String DEFAULT_SERVERIP = "jlambertvista"; 
	public static final int SERVERPORT = 40500; 
	public static final int DEFAULT_DEVICENUMBER = 0;
	public static String message = ""; 
	public static String response = "";
	public SharedPreferences prefs; 
	public static final String PREFS_NAME = "MyPrefsFile"; 
      
    public void run() { 
         try { 
           prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.me.getBaseContext());
           String serverName = prefs.getString(MainActivity.me.getString(R.string.servernamekey), DEFAULT_SERVERIP);
           int deviceNumber = Integer.parseInt(prefs.getString(MainActivity.me.getString(R.string.devicenumberkey), String.valueOf(DEFAULT_DEVICENUMBER)));
           /*SharedPreferences settings = this.
           public String server = settings.getString("SERVERIP","DEFAULT_SERVERIP"); 
           settings.*/ 

           InetAddress serverAddr = InetAddress.getByName(serverName); 
           //InetAddress serverAddr = InetAddress.getByName(); 
            
           Log.d("TCP", "C: Connecting..."); 
           Socket socket = new Socket(serverAddr, TCPClient.SERVERPORT + deviceNumber); 
           //String message = "CHAN +\n"; 
               try { 
                Log.d("TCP", "C: Sending: '" + message + "'"); 
                PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true); 
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 
                in.readLine();
                out.println(message); 
                response = in.readLine();
                Log.d("TCP", "C: Sent."); 
                  Log.d("TCP", "C: Done."); 
                  
             } catch(Exception e) { 
                 Log.e("TCP", "S: Error", e); 
                } finally { 
                  socket.close(); 
                } 
         } catch (Exception e) { 
              Log.e("TCP", "C: Error", e); 
         } 
    } 
} 


